package com.redis.distributed.service;

import com.redis.distributed.Utils.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.Callable;

@Service
@Slf4j
public class RedisService {
    @Autowired
    StringRedisTemplate redisTemplate;

    public boolean redisLock(long timeOut, Callable<Boolean> action) {
        log.info("redisLock timeOut "+timeOut);
        RedisLock redisLock = new RedisLock(redisTemplate, "redis_key",timeOut);

        try {
            boolean re=redisLock.lock();
            log.info("redisLock "+re);
            if (!re){
                return false;
            }

            action.call();
            return true;

        }catch (Exception e) {
            log.info(e.getMessage(), e);
        } finally {
            redisLock.unlock();
        }
        return false;

    }

}

